﻿using StarryEdge.Core;
using StarryEdge.Core.Models;
using StarryEdge.Core.Parameter;
using StarryEdge.Core.Tool;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StarryEdge.Parameter
{
    public class UIRoleManage : InitFileBase, IUIRoleManage
    {
        private List<UIRoleModel> models;

        public UIRoleManage(IStarryEdgeLog runLog) : base(runLog, "init", "uirole")
        {
            Init();
        }

        private void Init()
        {
            if (File.Exists(_path))
            {
                string str = base.Read();
                if (!string.IsNullOrEmpty(str))
                {
                    models = System.Text.Json.JsonSerializer.Deserialize<List<UIRoleModel>>(str);
                }
            }
            if (models == null)
            {
                models = new List<UIRoleModel>();
            }
        }

        public bool Save()
        {
            return Save(System.Text.Json.JsonSerializer.Serialize(models, OptionsHelper.Options));
        }

        public void AddUIRole(UIRoleModel uIRoleModel)
        {
            var model = models.FirstOrDefault(x => x.Title == uIRoleModel.Title && x.Name == uIRoleModel.Name);
            if (model == null)
            {
                models.Add(uIRoleModel);
            }
        }

        public UIRoleModel GetUIRoleModel(Func<UIRoleModel, bool> func)
        {
            return models.FirstOrDefault(func);
        }

        public IEnumerable<UIRoleModel> GetUIRoleModels(Func<UIRoleModel, bool> func)
        {
            return models.Where(func);
        }

        public void AddRole(UIRoleModel uIRoleModel, UIRoleItemModel uIRoleItem)
        {
            var model = models.FirstOrDefault(x => x.Title == uIRoleModel.Title && x.Name == uIRoleModel.Name);
            if (model != null)
            { 
                var item = model.GuidRoles.FirstOrDefault(x => x.Id == uIRoleItem.Id);
                if (item != null)
                {
                    item.Name = uIRoleItem.Name;
                }
                else
                {
                    model.GuidRoles.Add(uIRoleItem);
                }
            }
        }

        public void DeleteRole(UIRoleModel uIRoleModel, Guid uIRoleId)
        {
            var model = models.FirstOrDefault(x => x.Title == uIRoleModel.Title && x.Name == uIRoleModel.Name);
            if (model != null)
            {
                var item = model.GuidRoles.FirstOrDefault(x => x.Id == uIRoleId);
                if (item != null)
                {
                    model.GuidRoles.Remove(item);
                }
            }
        }
    }
}
